//
//  TopTabControl.m
//  TopTabControl
//
//  Created by wqh on 15-5-7.
//  Copyright (c) 2015年 Wqh. All rights reserved.
//

#import "TopTabControl.h"


#define TOPMENUCELL_ID @"topMenuCollectionViewCellId"
#define CONTENTMENUCELL_ID @"contentCollectionViewCellId"

@interface TopTabControl()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>
/*顶部菜单栏横向滑动的collectionView */
@property (nonatomic, strong) UICollectionView *topMenuCollectionView;

/*菜单下面横向滑动内容的collectionView */
@property (nonatomic, strong) UICollectionView *contentCollectionView;

/*指示器view */
@property (nonatomic, strong) UIView *indicatorView;

@property (nonatomic) NSIndexPath *lastIndexPath;
@end

@implementation TopTabControl

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.lastIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    }
    return self;
}


#pragma mark -override method
- (UICollectionView *)topMenuCollectionView {
    if (_topMenuCollectionView ==nil) {
        CGFloat topMenuHeight = TopTabControl_Default_TopMenuHeight;
        
        if ([self.datasource respondsToSelector:@selector(TopTabHeight:)]) {
            topMenuHeight = [self.datasource TopTabHeight:self];
        }
   
        
        CGFloat topMenuWidth = self.bounds.size.width;
        if ([self.datasource respondsToSelector:@selector(TopTabWidth:)]) {
            topMenuWidth = [self.datasource TopTabWidth:self];
        }
        
        CGFloat topMenuX = 0;
        if ([self.datasource respondsToSelector:@selector(TopTabX:)]) {
            topMenuX = [self.datasource TopTabX:self];
        }
 
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.itemSize = CGSizeMake(60, topMenuHeight);
        
        //注册topMenuCollectionViewCell
        _topMenuCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(topMenuX, 0, topMenuWidth, topMenuHeight) collectionViewLayout:flowLayout];
        _topMenuCollectionView.showsHorizontalScrollIndicator = NO;
        [_topMenuCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:TOPMENUCELL_ID];
        _topMenuCollectionView.delegate = self;
        _topMenuCollectionView.dataSource = self;
        
        [self addSubview:_topMenuCollectionView];
        _topMenuCollectionView.backgroundColor = [UIColor clearColor];
    }
    return _topMenuCollectionView;
}

- (UICollectionView *)contentCollectionView {
    if (_contentCollectionView == nil) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;

        flowLayout.itemSize = CGSizeMake(kScreenWidth,kScreenHeight-64-49);
       
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _contentCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, [self getMenuHeight], kScreenWidth, kScreenHeight-64-49) collectionViewLayout:flowLayout];
      
        _contentCollectionView.showsHorizontalScrollIndicator = NO;
        _contentCollectionView.backgroundColor = [UIColor grayColor];
        
        _contentCollectionView.delegate = self;
        _contentCollectionView.dataSource =self;
        
        //注册contentCollectionViewCell
        [_contentCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CONTENTMENUCELL_ID];
        _contentCollectionView.pagingEnabled = YES;
        [self addSubview:_contentCollectionView];
    }
    return _contentCollectionView;
}


- (void)setShowIndicatorView:(BOOL)showIndicatorView {
    if (showIndicatorView) {
        
        _indicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, [self getMenuHeight]-TopTabControl_Default_IndicatorHeight, 60, TopTabControl_Default_IndicatorHeight)];
        
        _indicatorView.backgroundColor = [UIColor customBlueColor];
        [self.topMenuCollectionView addSubview:_indicatorView];
        [self.topMenuCollectionView bringSubviewToFront:_indicatorView];
        
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if ([self.datasource respondsToSelector:@selector(TopTabMenuCount:)]) {
        return [self.datasource TopTabMenuCount:self];
    }else {
        return 0;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //如果是topMenuCollectionView
    if (collectionView == self.topMenuCollectionView) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:TOPMENUCELL_ID forIndexPath:indexPath];
        
        [[cell subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
        
        if ([self.datasource respondsToSelector:@selector(TopTabControl:itemAtIndex:)]) {
            TopTabMenuItem *item = [self.datasource TopTabControl:self itemAtIndex:indexPath.row];

            [cell addSubview:item];
            if (indexPath.row == self.lastIndexPath.row) {
                [[[item subviews ] lastObject] setSelected:YES];
            }
            
        }
        
        
        
        return cell;
    }
    
    //如果是contentCollectionView
    if (collectionView == self.contentCollectionView) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CONTENTMENUCELL_ID forIndexPath:indexPath];
        [[cell subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
        if ([self.datasource respondsToSelector:@selector(TopTabControl:pageAtIndex:)]) {
            TopTabPage *page = [self.datasource TopTabControl:self pageAtIndex:indexPath.row ];
            [cell addSubview:page];
        }
        return cell;
    }
    return [[UICollectionViewCell alloc] initWithFrame:CGRectZero];
}


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.topMenuCollectionView) {
        [self.contentCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        UIButton *lastButton = [[[[[collectionView cellForItemAtIndexPath:self.lastIndexPath] subviews] lastObject] subviews] lastObject];
        lastButton.selected = NO;
        self.lastIndexPath = indexPath;
        UIButton *button = [[[[cell subviews] lastObject] subviews] lastObject];
        button.selected = YES;
       
        
    }
}


#pragma mark - UIScrollViewDelegate 

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //记录当前页数
    self.pageIndex = self.contentCollectionView.contentOffset.x/self.bounds.size.width;
   
    //只要轻微滑动contentView 指示器就会跟这滑动
    [self updateIndicatorPosition];
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.contentCollectionView) {
        [self handleEndScroll];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
}

#pragma mark - public method
- (void)reloadData {
    [self.topMenuCollectionView reloadData];
    [self.contentCollectionView reloadData];
    
    
    
}


#pragma mark - private method
- (CGFloat)getMenuHeight {
    if ([self.datasource respondsToSelector:@selector(TopTabHeight:)]) {
        return [self.datasource TopTabHeight:self];
    }else {
        return TopTabControl_Default_TopMenuHeight;
    }
}

- (void)updateIndicatorPosition {
   
    float x = self.contentCollectionView.contentOffset.x/self.contentCollectionView.contentSize.width;
    if (self.contentCollectionView.contentSize.width!=0) {
        self.indicatorView.frame = CGRectMake(x*self.topMenuCollectionView.contentSize.width, [self getMenuHeight] - TopTabControl_Default_IndicatorHeight , 60, TopTabControl_Default_IndicatorHeight);
    }
}

//contentCollectionView停止滚动的时候调用
- (void)handleEndScroll {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.pageIndex inSection:0];
    [self.topMenuCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    //设置button为选中状态
    UIButton *lastButton = [[[[[self.topMenuCollectionView cellForItemAtIndexPath:self.lastIndexPath] subviews] lastObject] subviews] lastObject];
    lastButton.selected = NO;
    //将当前button设置为选中状态
    UIButton *button = [[[[[self.topMenuCollectionView cellForItemAtIndexPath:indexPath] subviews] lastObject] subviews] lastObject];
    //记录当前button的w位置
    self.lastIndexPath = indexPath;
    
    
    button.selected = YES;
    
}


- (void)displayPageAtIndex:(NSUInteger)pageIndex {
    
}

@end
